import { NextResponse } from 'next/server';
import { AppDataSource } from '@/database';
import { Todo } from '@/entities/Todo';

// 初始化数据库连接
const initializeDB = async () => {
  if (!AppDataSource.isInitialized) {
    await AppDataSource.initialize();
  }
};

// GET /api/todos
export async function GET() {
  try {
    await initializeDB();
    const todoRepository = AppDataSource.getRepository(Todo);
    const todos = await todoRepository.find();
    return NextResponse.json(todos);
  } catch (error) {
    console.error('Error fetching todos:', error);
    return NextResponse.json(
      { error: 'Failed to fetch todos' },
      { status: 500 }
    );
  }
}

// POST /api/todos
export async function POST(request: Request) {
  try {
    await initializeDB();
    const { text, plannedCompletionDate } = await request.json();
    
    if (!text) {
      return NextResponse.json(
        { error: 'Text is required' },
        { status: 400 }
      );
    }

    const todoRepository = AppDataSource.getRepository(Todo);
    const todo = new Todo();
    todo.text = text;
    todo.completed = false;
    todo.createdAt = new Date();
    todo.updatedAt = new Date();
    
    if (plannedCompletionDate) {
      todo.plannedCompletionDate = new Date(plannedCompletionDate);
    }
    
    const savedTodo = await todoRepository.save(todo);
    return NextResponse.json(savedTodo);
  } catch (error) {
    console.error('Error creating todo:', error);
    return NextResponse.json(
      { error: 'Failed to create todo' },
      { status: 500 }
    );
  }
} 